package com.pzhu.gmall.passport.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.pzhu.gmall.bean.UserMember;
import com.pzhu.gmall.commons.utils.MD5Utils;
import com.pzhu.gmall.service.UserService;
import com.pzhu.gmall.web.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 刘鹏 liupeng
 * @date 2019/11/19
 **/
@Controller
public class PassPortController {

    @Reference
    private UserService userService;

    @Value("${jwt.key}")
    private String key;

    @RequestMapping("index")
    public String index(String ReturnUrl, ModelMap modelMap) {

        modelMap.put("ReturnUrl", ReturnUrl);
        return "index";
    }

    @RequestMapping("verify")
    @ResponseBody
    public String verify(String token, String ip) {
        String result = new String();
        Map<String, Object> decode = JwtUtil.decode(token, key, ip);
        if (decode == null) {
            result = "fail";
        }
        String memberId = (String) decode.get("memberId");
        String nickname = (String) decode.get("nickname");
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("memberId", memberId);
        resultMap.put("nickname", nickname);
        result = JSON.toJSONString(resultMap);
        return result;
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(UserMember userMember, HttpServletRequest request) {
        //调用用户服务验证用户名和密码，返回token
        String token = null;
        UserMember userMemberLogin = userService.login(userMember);
        Map<String, Object> userInfoMap = new HashMap<>();
        if (userMember != null) {
            userInfoMap.put("memberId", userMember.getId());
            userInfoMap.put("nickname", userMember.getNickname());
            /* 通过nginx章法的客户端Ip */
            String ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ip)) {
                ip = MD5Utils.md5("127.0.0.1");
            }
            token = JwtUtil.encode(key, userInfoMap, ip);
            if (StringUtils.isBlank(token)) {
                token = "fail";
            }
        }
        return token;
    }

}
